<!-- equipmentLedger -->
<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag" :class="isCloseTree ? 'tag-nav-close' : ''">
        <div class="main-content">
          <div class="form-box">
            <BasicForm @register="registerForm" />
          </div>
          <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :clickToRowSelect="false"
            :showIndexColumn="true"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="hasPermission(['3-1-update', '3-1-del']) ? actionColumn : undefined"
            rowKey="code"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action' && hasPermission(['3-1-update', '3-1-del'])">
                <TableAction
                  :actions="[
                    {
                      label: '编辑',
                      icon: 'ant-design:edit-outlined',
                      ifShow: hasPermission('3-1-update'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleEdit(record);
                      },
                    },
                    {
                      label: '删除',
                      icon: 'ant-design:delete-outlined',
                      ifShow: hasPermission('3-1-del'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleDelete(record);
                      },
                    },
                  ]"
                />
              </template>
              <template v-else-if="column.key === 'Images'">
                <TableImg :size="30" :simpleShow="true" :imgList="record.Images" />
              </template>
            </template>
            <template #toolbar>
              <template v-if="true">
                <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
                <a-button class="btn-box-item" type="primary" @click="throttleSubmit"
                  >查询</a-button
                >
                <a-button
                  type="primary"
                  @click="handleShowSelect"
                  v-if="hasPermission('3-1-mesAddress')"
                >
                  MES地址配置
                </a-button>
                <a-button
                  type="primary"
                  @click="throttleSyncMesData"
                  v-if="hasPermission('3-1-mesSynchronize')"
                  :loading="loadingByBtn"
                >
                  同步MES数据
                </a-button>
                <a-button
                  type="primary"
                  @click="handleAllClear"
                  :loading="loadingByBtn"
                  v-if="hasPermission('3-1-clear')"
                >
                  清空
                </a-button>
                <a-button type="primary" @click="handleAdd" v-if="hasPermission('3-1-add')">
                  新增
                </a-button>
                <a-button
                  v-if="isShowBatchDel && hasPermission('3-1-batchDel')"
                  type="primary"
                  @click="handleBatchDel"
                  :loading="loadingByBtn"
                >
                  批量删除
                </a-button>
                <a-button type="primary" @click="handleSave" v-if="hasPermission('3-1-save')">
                  保存到配置文件
                </a-button>
              </template>
            </template>
          </BasicTable>
          <div class="flex py-2 items-center justify-end pagination-box">
            <a-pagination
              :show-total="(total) => `共 ${total} 条数据`"
              showSizeChanger
              size="small"
              :current="paginationInfo.data.current"
              :pageSize="paginationInfo.data.pageSize"
              :total="paginationInfo.data.total"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 新增或编辑的弹窗 -->
    <modelByDetail
      :info="detailForm"
      :deviceTypeList="deviceTypeList"
      :deviceOwnershipList="treeDataPro"
      @register="registerByDetail"
      @submit-success="handelUpateTable"
    />
    <modelBySelect @register="registerBySelect" @submit-success="handelSuccessBySelect" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  // eslint-disable-next-line
  import { ref, onMounted, reactive, h, unref, nextTick } from 'vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, TableAction, useTable, TableImg } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  // eslint-disable-next-line
  import { Icon } from '/@/components/Icon';
  // import { cloneDeep } from 'lodash-es';
  import { Pagination } from 'ant-design-vue';
  import { saveConfig } from '/@/api/tag/index';
  import modelByDetail from '/@/views/project/equipmentLedger/components/modelByDetail.vue';
  import modelBySelect from '/@/views/project/equipmentLedger/components/modelBySelect.vue';
  // eslint-disable-next-line
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import {
    updateequipments,
    getequipmentsbyenterprise,
    batchdeleteequipment,
    removeequipment,
    clearequipment,
  } from '/@/api/equipmentLedger/index';
  import { getenterprisetree } from '/@/api/enterprise/index';
  import { getdevicetypes } from '/@/api/equipmentType/index';
  import { getdevicemodels, getdatalist } from '/@/api/equipmentModel/index';
  import { useDebounceFn } from '@vueuse/core';
  import { getUrlProfix } from '/@/utils/index';

  const throttleSyncMesData = useDebounceFn(handleSyncMesData, 500);

  const APagination = Pagination;
  let searchDriver = ref('');
  let treeDataPro = ref([]);
  let loading = ref(false);
  let tableData = reactive([]);
  let loadingByBtn = ref(false);
  let isShowBatchDel = ref(false);
  // 企业信息
  let enterpriseInfo = {};
  // 设备类型
  let deviceTypeList = [];
  // 设备型号
  let deviceModelList = [];
  // 设备类别
  let CategoryObj = [];
  //使用状态
  let statusList = [];
  let isCloseTree = ref(false);
  // let treeClickCount = 0;
  let detailForm = reactive({
    type: 'add',
    data: {},
    enterpriseInfo: {},
  });
  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  // eslint-disable-next-line
  const treeRef = ref<Nullable<TreeActionType>>(null);
  const { hasPermission } = usePermission();
  const { createConfirm, createMessage } = useMessage();
  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerBySelect, { openModal: openModalBySelect, closeModal: closeModalBySelect }] =
    useModal();
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'SearchCode',
      component: 'Input',
      label: '设备编码：',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'SearchDeviceName',
      component: 'Input',
      label: '设备名称：',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'SearchModelCode',
      component: 'Select',
      label: '设备型号：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
      },
    },
    {
      field: 'SearchCategory',
      component: 'Select',
      label: '设备类别：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
      },
    },
    {
      field: 'TypeCode',
      component: 'Select',
      label: '设备类型：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
      },
    },
    {
      field: 'Manufacturer',
      component: 'Input',
      label: '生产商',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'UseStatsCode',
      component: 'Select',
      label: '使用状态：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
      },
    },
  ];
  const [registerForm, { validateFields, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { t } = useI18n();
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });

  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '设备图片',
      dataIndex: 'Images',
      width: 120,
    },
    {
      title: '设备编码',
      dataIndex: 'Code',
    },
    {
      title: '设备名称',
      dataIndex: 'Name',
    },
    {
      title: '设备类型',
      dataIndex: 'Type_text',
    },
    {
      title: '设备类别',
      dataIndex: 'Category_text',
      width: 80,
    },
    {
      title: '设备型号',
      dataIndex: 'Mode_text',
      width: 150,
    },
    {
      title: '使用状态',
      dataIndex: 'UseStatus_text',
      width: 80,
    },
    {
      title: '公司/工厂',
      dataIndex: 'Factory',
    },
    {
      title: '车间',
      dataIndex: 'Workshop',
    },
    {
      title: '生产资源',
      dataIndex: 'ProductionLine',
    },
    {
      title: '生产商',
      dataIndex: 'Manufacturer',
    },
    {
      title: '是否虚拟设备',
      dataIndex: 'IsFictitious_text',
    },
  ];
  // 操作栏
  let actionColumn = {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };

  const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
  // 获取设备类型
  async function getDeviceTypes() {
    try {
      loading.value = true;

      let res = await getdevicetypes([
        {
          PageNO: 1,
          PageSize: 500,
        },
      ]);
      deviceTypeList = res.Rows;
      updateSchema({
        field: 'TypeCode',
        componentProps: {
          options: deviceTypeList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //获取设备类别
  async function getSearchCategory() {
    try {
      loading.value = true;

      let res = await getdatalist([
        {
          Code: 'equipment_category',
        },
      ]);

      CategoryObj = res;
      updateSchema({
        field: 'SearchCategory',
        componentProps: {
          options: CategoryObj,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //获取使用状态
  async function getStatus() {
    try {
      loading.value = true;

      let res = await getdatalist([
        {
          Code: 'equipment_status',
        },
      ]);

      statusList = res;
      updateSchema({
        field: 'UseStatsCode',
        componentProps: {
          options: statusList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  // 获取设备型号
  async function getDeviceModels() {
    try {
      loading.value = true;

      let res = await getdevicemodels([
        {
          PageNO: 1,
          PageSize: 50,
        },
      ]);
      deviceModelList = res.Rows;

      updateSchema({
        field: 'SearchModelCode',
        componentProps: {
          options: deviceModelList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 重置按钮点击事件
  async function handleResetFields() {
    initSearch();
    getTableData();
  }
  // 重置搜索条件
  function initSearch() {
    setFieldsValue({
      TypeCode: '',
      SearchModelCode: '',
      SearchCategory: '',
      Manufacturer: '',
      SearchDeviceName: '',
      UseStatsCode: '',
      SearchCode: '',
    });
    paginationInfo.data.current = 1;
  }
  // 查询按钮点击事件
  async function handleSubmit() {
    try {
      let res = await validateFields();
      getTableData(res);
    } catch {}
  }
  // 折叠左侧区域
  // function handleSideBarClick() {
  //   isCloseTree.value = !isCloseTree.value;
  // }
  // 展开 折叠
  // function expandAll(checkAll) {
  //   getTree().expandAll(checkAll);
  // }
  // 获取树数据
  async function initData(isOpenTree = false) {
    loading.value = true;
    let resByTree = await getenterprisetree(
      searchDriver.value ? [false, searchDriver.value] : [false, null],
    );
    treeDataPro.value = resByTree || [];
    if (resByTree.length > 0) {
      enterpriseInfo = resByTree[0];
      initSearch();
      getTableData();
    }
    // if (isOpenTree) {
    //   nextTick(() => {
    //     getTree().filterByLevel(1);
    //   });
    // }

    loading.value = false;
  }
  // 获取树dom
  // function getTree() {
  //   const tree = unref(treeRef);
  //   if (!tree) {
  //     throw new Error('tree is null!');
  //   }
  //   return tree;
  // }
  // 树点击事件
  // eslint-disable-next-line
  function handleTreeSelect(_e, info) {
    let val = info.node || {};
    enterpriseInfo = val;
    initSearch();
    getTableData();
    // treeClickCount++;

    // //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
    // if (treeClickCount >= 2) {
    //   return;
    // }
    // //计时器,计算300毫秒为单位,可自行修改
    // setTimeout(() => {
    //   if (treeClickCount == 1) {
    //     //把次数归零
    //     treeClickCount = 0;
    //     // 单击事件
    //     handleClickByTree(info);
    //   } else if (treeClickCount > 1) {
    //     //把次数归零
    //     treeClickCount = 0;
    //     //双击事件
    //     handleDbClickByTree(info);
    //   }
    // }, 300);
  }
  // 双击事件
  // function handleDbClickByTree(info) {
  //   let val = info.node || {};
  //   console.log(`output->val`, val);
  // }
  // 新增或编辑成功事件
  function handelUpateTable() {
    detailForm.type = 'add';
    detailForm.data = {};
    detailForm.enterpriseInfo = {};
    closeModalByDetail();
    getTableData();
  }
  // 搜索树
  // eslint-disable-next-line
  function onSearchDriver() {
    initData();
  }
  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  // 保存
  function handleSave() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `此操作将会把页面内容保存到配置文件，是否确认该操作？`),
      onOk: async () => {
        try {
          await saveConfig();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  // 新增
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = {};
    detailForm.enterpriseInfo = {};
    openModalByDetail();
  }
  // 清空
  function handleAllClear() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '危险操作'),
      okText: '是',
      content: () => h('span', `是否清空所有设备`),
      onOk: async () => {
        loadingByBtn.value = true;
        try {
          await clearequipment();

          createMessage.success(t('layout.setting.operatingTitle'));
          loadingByBtn.value = false;
          getTableData();
        } catch (error) {
          loadingByBtn.value = false;
        }
      },
    });
  }
  // 批量删除
  function handleBatchDel() {
    let keys = getSelectRowKeys();
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除选择的设备（${keys.join('、')}）`),
      onOk: async () => {
        loadingByBtn.value = true;
        try {
          await batchdeleteequipment([keys]);

          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
          loadingByBtn.value = false;
        } catch (error) {
          loadingByBtn.value = false;
        }
      },
    });
  }
  // 同步mes数据
  async function handleSyncMesData() {
    loadingByBtn.value = true;
    try {
      await updateequipments();
      getTableData();
      createMessage.success('同步成功');
      loadingByBtn.value = false;
    } catch (error) {
      loadingByBtn.value = false;
    }
  }
  // 编辑
  function handleEdit(params) {
    detailForm.type = 'update';
    detailForm.data = params;
    detailForm.enterpriseInfo = enterpriseInfo;

    openModalByDetail();
  }
  // 删除
  function handleDelete(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该设备（${params.code}）`),
      onOk: async () => {
        loading.value = true;
        try {
          await removeequipment([params.Id]);

          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      },
    });
  }
  // 表格选中事件
  function onChangeByTable(selectedRowKeys) {
    isShowBatchDel.value = selectedRowKeys.length > 0;
  }

  // 获取设备集合
  async function getTableData(params = {}) {
    clearSelectedRowKeys();
    try {
      loading.value = true;
      let res = await getequipmentsbyenterprise([
        {
          PageNO: paginationInfo.data.current,
          PageSize: paginationInfo.data.pageSize,
          ...params,
        },
      ]);
      paginationInfo.data.total = res.Total;
      let imgUrl = getUrlProfix();
      tableData = res.Items.map((item) => {
        // let {
        //   ModelCode,
        //   ModelName,
        //   TechnicalSpec,
        //   Manufacturer,
        //   DeviceTypeInfo = {},
        // } = item.DeviceModelInfo;
        // item.ModelCode = ModelCode;
        // item.ModelName = ModelName;
        // item.TechnicalSpec = TechnicalSpec;
        // item.Manufacturer = Manufacturer;
        // item.TypeName = DeviceTypeInfo.TypeName;
        // item.typeId = DeviceTypeInfo.Id;
        // item.type_category_cn = CategoryObj[DeviceTypeInfo.Category];
        // item.useStatusCn =
        //   +item.UseStatus === 0 ? '使用中' : +item.UseStatus === 0 ? '闲置' : '封存';
        //增加图片空的判断
        let img = item.Image;
        if (typeof img !== 'undefined' && img != null && img !== '') {
          item.Images = item.Images.map((val) => {
            return imgUrl + val;
          });
        }
        return item;
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 显示MES地址下拉框弹窗
  function handleShowSelect() {
    openModalBySelect();
  }
  function handelSuccessBySelect() {
    closeModalBySelect();
  }
  onMounted(async () => {
    initData(true);
    getDeviceTypes();
    getDeviceModels();
    getSearchCategory();
    getStatus();
    // getTableData();
  });
</script>
<script lang="ts">
  export default {
    name: 'EquipmentLedgerIndexPage',
  };
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .search-box {
        display: flex;
        align-items: center;

        > .ant-btn-sm {
          height: 32px;
        }
      }

      .main-nav {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 240px;
        height: calc(100%);
        padding: 8px;
        box-sizing: border-box;
        overflow: auto;
        border-right: 1px solid #ccc;

        ::v-deep(.vben-tree__title) {
          user-select: none !important;
        }
      }

      .main-sidebar {
        position: absolute;
        top: 0;
        left: 240px;
        bottom: 0;
        width: 12px;
        border-radius: 5px;
        cursor: pointer;
        user-select: none;

        .close-btn {
          position: absolute;
          top: 50%;
          left: 0;
          width: 12px;
          height: 30px;
          margin-top: -50%;

          line-height: 30px;
          text-align: center;
          background: #7dcdfe;
          border-radius: 6px;
          color: #fff;

          > span {
            font-size: 12px !important;
          }
        }
      }

      .main-sidebar:hover {
        background-color: #e2e3e5;
      }

      .main-content {
        position: relative;
        height: 100%;
        //margin-left: 260px;
        overflow: hidden;

        .pagination-box {
          z-index: 9;
          padding: 10px 5px;
          box-sizing: border-box;
          position: absolute;
          width: 100%;
          bottom: 0;
          left: 0;
          right: 0;
          background-color: #fff;
        }
      }

      .main-content::after {
        content: '';
        display: block;
        width: 100%;
        height: 45px;
      }
    }

    .tag-nav-close {
      .main-nav {
        left: -260px;
      }

      .main-sidebar {
        left: 0;
      }

      .main-content {
        margin-left: 20px;
      }
    }
  }

  .form-box {
    padding: 5px;

    ::v-deep(.ant-form-item) {
      margin: 0 5px;
      margin-bottom: 8px;
    }
  }
</style>
